﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using System.Web;
using 泛微oa新建流程表单;


namespace StandardInterface
{
    public class CreateRequestinfo1690
    {
        // 第一步做一次就行了  记录下来
        /// <summary>
        /// 模拟缓存服务
        /// </summary>
        private static readonly Dictionary<string, string> SYSTEM_CACHE = new Dictionary<string, string>();

        /// <summary>
        /// ecology 系统发放的授权许可证(appid)
        /// </summary>
        private static readonly string APPID = "a677fb06-42f2-4672-af7e-c7bdf84a0079";

        private static readonly HttpClient httpClient = new HttpClient();

        public static async Task Main(string[] args)
        {
            // 2882 测试流程创建用这个id发起    需要测试流程的话workflowid用2082正式流程1690 换人创建要清一次cookie会有缓存
            // 在 .NET 中，HttpClient 默认会自动管理 cookies，如果需要清除可以重新创建实例
            httpClient.DefaultRequestHeaders.Clear();

            await TestRestful("http://oa.maxwell-gp.com.cn:8090", "/api/workflow/paService/doCreateRequest", "");
        }

        /// <summary>
        /// 第一步：
        /// 调用 ecology 注册接口,根据 appid 进行注册,将返回服务端公钥和 Secret 信息
        /// 好像是30分钟过期
        /// </summary>
        public static async Task<Dictionary<string, object>> TestGetoken(string address)
        {
            // 从系统缓存或者数据库中获取 ECOLOGY 系统公钥和 Secret 信息
            string secret = "7e34ac04-66e4-4be9-ac3c-89c025367e07";
            string spk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC275dG8DgkX+1ORNNYZMsNnXSfo5FSQxVe5t/zx5FLSDqZAfUFW/HP+9QzF/Wjj30r+3N9uX3uSY1IpAaAZ4YfKpkJ2I6/2TzA2AJpV9eVfbOB6wRvhaDia8eJILNK3SF6sHtBr94z+0Y5jnm76jPc5wApqKNhoQTgD2fXFnQ0ywIDAQAB";

            SYSTEM_CACHE["SERVER_PUBLIC_KEY"] = spk;
            // ECOLOGY 返回的系统密钥
            SYSTEM_CACHE["SERVER_SECRET"] = secret;

            // 对秘钥进行加密传输，防止篡改数据
            string encryptSecret = RSAEncryptPr.RSAEncrypt(secret, spk);

            // 调用 ECOLOGY 系统接口进行注册
            var request = new HttpRequestMessage(HttpMethod.Post, address + "/api/ec/dev/auth/applytoken");
            request.Headers.Add("appid", APPID);
            request.Headers.Add("secret", encryptSecret);
            request.Headers.Add("time", "3600");

            var response = await httpClient.SendAsync(request);
            string responseData = await response.Content.ReadAsStringAsync();

            Console.WriteLine("TestGetoken()：" + responseData);

            var datas = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseData);
            // ECOLOGY 返回的 token
            // TODO 为 Token 缓存设置过期时间
            SYSTEM_CACHE["SERVER_TOKEN"] = datas["token"]?.ToString() ?? "";

            return datas;
        }

        public static async Task<string> TestRestful(string address, string api, string jsonParams)
        {
            var tokenData = await TestGetoken(address);
            string token = tokenData["token"]?.ToString();
            string spk = SYSTEM_CACHE["SERVER_PUBLIC_KEY"];

            // 对用户信息进行加密传输,暂仅支持传输 OA 用户 ID
            string encryptUserid = RSAEncryptPr.RSAEncrypt("23844", spk);

            // 构建请求体
            var formData = new Dictionary<string, string>
            {
                {"workflowId", "2383"},
                {"requestName", "test20250809"},
                {"mainData", "["
                    + "{'fieldName':'xm','fieldValue':'jjjj'}"


                    + "]"

                 },
                 {"detailData", "[" +
                 "{'tableDBName':'formtable_main_837_dt1','workflowRequestTableRecords':[" +
                 "{'recordOrder':0,'workflowRequestTableFields':[" +
                 "{'fieldName':'xm','fieldValue':'测试产品2'}," +
                 "{'fieldName':'mc','fieldValue':'test'}]}," +
                 "{'recordOrder':0,'workflowRequestTableFields':[" +
                 "{'fieldName':'xm','fieldValue':'测试产品1'}," +
                 "{'fieldName':'mc','fieldValue':'tes'}]}" +
                 "]}]" 
                 }
                 //"{'tableDBName':'formtable_main_760_dt4','workflowRequestTableRecords':[" +
                 //"{'recordOrder':0,'workflowRequestTableFields':[" +
                 //"{'fieldName':'xh','fieldValue':'0'}," +
                 //"{'fieldName':'lb','fieldValue':'40'}," +
                 //"{'fieldName':'sl','fieldValue':'10'}," +
                 //"{'fieldName':'dw','fieldValue':'10'}," +
                 //"{'fieldName':'wsdjy','fieldValue':'0'}," +
                 //"{'fieldName':'zbkbl','fieldValue':'40'}]}]}]"
                







        };

            var request = new HttpRequestMessage(HttpMethod.Post, address + api);
            request.Headers.Add("appid", APPID);
            request.Headers.Add("token", token);
            request.Headers.Add("userid", encryptUserid);
            request.Content = new FormUrlEncodedContent(formData);

            var response = await httpClient.SendAsync(request);
            string data = await response.Content.ReadAsStringAsync();

            Console.WriteLine("token:" + token);
            Console.WriteLine("userid:" + encryptUserid);
            Console.WriteLine("TestRestful()：" + data);

            return data;
        }

       

        /// <summary>
        /// 将 PEM 格式的公钥转换为 XML 格式
        /// </summary>
        private static string ConvertPublicKeyToXml(string publicKey)
        {
            // 这里需要根据实际的 PEM 格式进行解析
            // 简化处理，假设已经是 XML 格式或者进行适当转换
            // 实际使用时可能需要更复杂的转换逻辑
            if (publicKey.Contains("<RSAKeyValue>"))
                return publicKey;

            // 简单示例，实际需要根据 PEM 格式进行解析
            return $"<RSAKeyValue><Modulus>{publicKey}</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
        }
    }
}